#!/bin/bash
# build_exosip2.sh - 编译 libexosip2 为 Android armeabi-v7a
# 已修复：头文件找不到、Windows库链接错误等问题
# 在 WSL 中运行：bash build_exosip2.sh

# 设置路径（请根据实际情况修改）
SOURCE_DIR="$(pwd)"
NDK_DIR="/home/vm/android-ndk-r21d"
OSIP_INSTALL_DIR="/home/vm/GB28181/sip/libosip2-5.3.0/install-android-armeabi-v7a"
BUILD_DIR="$SOURCE_DIR/build-android-armeabi-v7a"
INSTALL_DIR="$SOURCE_DIR/install-android-armeabi-v7a"

# 检查源码目录
if [ ! -d "$SOURCE_DIR" ]; then
    echo "❌ 错误：源码目录不存在！$SOURCE_DIR"
    exit 1
fi

# 检查 NDK 目录
if [ ! -d "$NDK_DIR" ]; then
    echo "❌ 错误：NDK 目录不存在！$NDK_DIR"
    exit 1
fi

# 检查 osip 头文件和库
if [ ! -d "$OSIP_INSTALL_DIR/include" ] || [ ! -d "$OSIP_INSTALL_DIR/lib" ]; then
    echo "❌ 错误：找不到 osip2 的头文件或库！请确认路径："
    echo "$OSIP_INSTALL_DIR"
    exit 1
fi

# 检查 configure 脚本
if [ ! -f "$SOURCE_DIR/configure" ]; then
    echo "❌ 错误：找不到 configure 脚本！请确认 libexosip2-5.3.0 已正确解压。"
    exit 1
fi

# === 关键修复：删除旧的 build 目录，避免缓存问题 ===
echo "🧹 正在清理旧的构建目录..."
rm -rf "$BUILD_DIR"

# 创建构建和安装目录
mkdir -p "$BUILD_DIR"
mkdir -p "$INSTALL_DIR"

echo "✅ 准备工作完成，开始配置..."

cd "$BUILD_DIR" || exit 1

# 设置 Android 编译参数
ANDROID_API=26
TOOLCHAIN_DIR="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64"
CC="$TOOLCHAIN_DIR/bin/armv7a-linux-androideabi$ANDROID_API-clang"
CXX="$TOOLCHAIN_DIR/bin/armv7a-linux-androideabi$ANDROID_API-clang++"
CFLAGS="-fPIC -DANDROID -D__ANDROID_API__=$ANDROID_API -I$OSIP_INSTALL_DIR/include"
CXXFLAGS="$CFLAGS"
LDFLAGS="-L$OSIP_INSTALL_DIR/lib -losip2 -llog -Wl,--allow-multiple-definition"
HOST="arm-linux-androideabi"

LIBS="-llog -losip2" \
"$SOURCE_DIR/configure" \
    --host=arm-linux-androideabi \
    --build=x86_64-pc-linux-gnu \
    --target=arm-linux-androideabi \
    --prefix="$INSTALL_DIR" \
    --enable-shared \
    --disable-static \
    --disable-dependency-tracking \
    --with-osip="$OSIP_INSTALL_DIR" \
    --disable-win32-dll \
    CC="$CC" \
    CXX="$CXX" \
    CFLAGS="-fPIC -DANDROID -D__ANDROID_API__=$ANDROID_API -I$OSIP_INSTALL_DIR/include" \
    CXXFLAGS="-fPIC -DANDROID -D__ANDROID_API__=$ANDROID_API -I$OSIP_INSTALL_DIR/include" \
    LDFLAGS="-L$OSIP_INSTALL_DIR/lib -llog -losip2 -Wl,--allow-multiple-definition"

if [ $? -ne 0 ]; then
    echo "❌ configure 失败！"
    echo "请检查："
    echo "1. NDK 路径是否正确: $NDK_DIR"
    echo "2. 编译器是否存在: $CC"
    echo "3. osip2 路径是否正确: $OSIP_INSTALL_DIR"
    exit 1
fi

echo "✅ configure 成功，开始编译..."
echo "🛠️  正在编译 libexosip2..."

make -j4

if [ $? -ne 0 ]; then
    echo "❌ 编译失败！"
    exit 1
fi

echo "✅ 编译成功，开始安装..."
make install

echo ""
echo "🎉🎉🎉 编译和安装成功！ 🎉🎉🎉"
echo ""
echo "生成的库文件："
echo "$INSTALL_DIR/lib/libexosip2.so"
echo ""
echo "头文件："
echo "$INSTALL_DIR/include/exosip2/"
echo ""
echo "💡 使用说明："
echo "1. 将 libosip2.so 和 libexosip2.so 一起放入 Android 项目的 jniLibs/armeabi-v7a/"
echo "2. 在 C/C++ 代码中 #include <exosip2/eXosip.h>"
echo "3. 链接时确保 -lexosip2 和 -losip2 都被包含"
echo ""